package com.example.flowableoa.service.Impl;

import com.example.comment_oa.pojos_vo.flowableVo.taskVo;
import com.example.flowableoa.config.CustomProcessDiagramGenerator;
import com.example.flowableoa.domain.dto.FlowTaskDto;
import com.example.flowableoa.domain.dto.HistoricTaskInstanceDto;
import com.example.flowableoa.factory.FlowServiceFactory;
import com.example.flowableoa.service.IFlowTaskService;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.task.Comment;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.flowable.variable.api.persistence.entity.VariableInstance;
import org.springframework.stereotype.Service;


import java.io.InputStream;
import java.util.*;

@Service
public class IFlowTaskServiceImpl extends FlowServiceFactory implements IFlowTaskService {



    @Override
    public  List<FlowTaskDto> myTodoTaskList(String gongHao) {
        List<Task> taskQuery = taskService.createTaskQuery()
                .active() // 激活的任务
                .taskAssignee(gongHao)
                .orderByTaskCreateTime()
                .desc()
                .list();

        List<FlowTaskDto> list = new ArrayList<>();

        if(taskQuery != null && taskQuery.size() > 0){
            for (Task task : taskQuery) {
                FlowTaskDto flowTask = new FlowTaskDto();
                //  查询 当前的Task信息
                flowTask.setTaskId(task.getId());
                // 处理人的ID， 约定账号唯一
                flowTask.setAssigneeId(gongHao);
                flowTask.setAssigneeName(task.getAssignee());
                flowTask.setCreateTime(task.getCreateTime());

                Map<String, VariableInstance> variableInstances = taskService.getVariableInstances(task.getId());
                // 绑定对应的流程变量
                flowTask.setVariableInstances(variableInstances);

                flowTask.setProcInsId(task.getProcessInstanceId());
                flowTask.setTaskName(task.getName());
                flowTask.setExecutionId(task.getExecutionId());
                flowTask.setTaskDefKey(task.getTaskDefinitionKey());

                // 查询流程定义的信息
                ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                        .processDefinitionId(task.getProcessDefinitionId())
                        .singleResult();
                flowTask.setProcDefId(task.getProcessDefinitionId());
                flowTask.setProcDefName(processDefinition.getName());
                flowTask.setProcDefVersion(processDefinition.getVersion());
                flowTask.setDeployId(processDefinition.getDeploymentId());

                // 流程发起人的信息
                HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                        .processInstanceId(task.getProcessInstanceId())
                        .singleResult();
                // 获取任务的发起人
                String startUserName = historicProcessInstance.getStartUserId();
                flowTask.setStartUserId(startUserName);

                //flowTask.setStartUserName(startUser.getNickName());
                flowTask.setStartTime(historicProcessInstance.getStartTime());
                list.add(flowTask);
            }

        }
        return list;
    }



    @Override
    public List<FlowTaskDto> mysendTaskList(String gongHao) {


        System.err.println(gongHao);
        List<HistoricProcessInstance> historicTaskInstances = historyService.createHistoricProcessInstanceQuery()
                .includeProcessVariables()
                .startedBy(gongHao)
                .orderByProcessInstanceStartTime()
                .desc()
                .list();

//        List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery()
//                .includeProcessVariables()
//                .finished()
//                .taskAssignee(gongHao)
//                .orderByHistoricTaskInstanceStartTime()
//                .desc()
//                .list();

        List<FlowTaskDto> list = new ArrayList<>();
        if(historicTaskInstances != null && historicTaskInstances.size() > 0){
            for (HistoricProcessInstance historicTaskInstance : historicTaskInstances) {


                FlowTaskDto flowTask = new FlowTaskDto();
                //  查询 当前的Task信息
                flowTask.setTaskId(historicTaskInstance.getId());
                // 处理人的ID， 约定账号唯一

                flowTask.setStartTime(historicTaskInstance.getStartTime());

                // 任务审批耗时
                //flowTask.setDuration(historicTaskInstance.getDurationInMillis()/1000+"秒");

            /*Map<String, VariableInstance> variableInstances = taskService.getVariableInstances(historicTaskInstance.getId());
            // 绑定对应的流程变量
            flowTask.setVariableInstances(variableInstances);*/
                // 绑定流程变量
                Map<String, Object> processVariables = historicTaskInstance.getProcessVariables();
                flowTask.setVariables(processVariables);

//                flowTask.setProcInsId(historicTaskInstance.getProcessInstanceId());
//                flowTask.setTaskName(historicTaskInstance.getName());
//                flowTask.setExecutionId(historicTaskInstance.getExecutionId());
//                flowTask.setTaskDefKey(historicTaskInstance.getTaskDefinitionKey());

                // 查询流程定义的信息
                ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                        .processDefinitionId(historicTaskInstance.getProcessDefinitionId())
                        .singleResult();
                flowTask.setProcDefId(historicTaskInstance.getProcessDefinitionId());
                flowTask.setProcDefName(processDefinition.getName());
                flowTask.setProcDefVersion(processDefinition.getVersion());
                flowTask.setDeployId(processDefinition.getDeploymentId());

                // 流程发起人的信息
//                HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
//                        .processInstanceId(historicTaskInstance.getProcessInstanceId())
//                        .singleResult();
                // 获取任务的发起人
//                String startUserName = historicProcessInstance.getStartUserId();
//                User startUser = userService.queryByUserName(startUserName);
                flowTask.setStartUserId(gongHao);

                //flowTask.setStartUserName(startUser.getNickName());
//                flowTask.setStartTime(historicProcessInstance.getStartTime());

                List<HistoricTaskInstanceDto> historicTaskInstanceDtos = new ArrayList<>();
                // 查询当前任务的流转信息
//                List<HistoricTaskInstance> taskHiInstances = historyService.createHistoricTaskInstanceQuery()
//                        .processInstanceId(historicTaskInstance.getProcessInstanceId())
//                        .orderByHistoricTaskInstanceStartTime()
//                        .asc()
//                        .list();
//                for (HistoricTaskInstance taskHiInstance : taskHiInstances) {
//                    HistoricTaskInstanceDto dto = new HistoricTaskInstanceDto();
//                    dto.setTaskId(taskHiInstance.getId());
//                    dto.setTaskName(taskHiInstance.getName());
//                    dto.setFinishTime(taskHiInstance.getEndTime());
//                    if(taskHiInstance.getDurationInMillis() != null){
//                        dto.setDuration(taskHiInstance.getDurationInMillis()/1000 + "秒");
//                    }
//                    User user1 = userService.queryByUserName(taskHiInstance.getAssignee());
//                    dto.setAssigneeName(user1.getNickName());
                    // 还需要根据 HistoricTaskInstance 找到对应的 审批意见
//                    List<Comment> processInstanceComments = taskService.getProcessInstanceComments(historicTaskInstance.getProcessInstanceId());
//                    for (Comment comment : processInstanceComments) {
//                        if(comment.getTaskId().equals(taskHiInstance.getId())){
//                            // 审批意见
//                            String fullMessage = comment.getFullMessage();
//                            dto.setComment(fullMessage);
//                        }
//                    }
//                    historicTaskInstanceDtos.add(dto);
//                }
//                flowTask.setTransferRecords(historicTaskInstanceDtos);
                //flowTask.setSt
                //System.err.println(flowTask);
                list.add(flowTask);
                // System.err.println(flowTask);
            }
        }



        return list;
    }

    @Override
    public InputStream diagram(String processId) {
       // System.err.println("???"+processId);
        String processDefinitionId;
        // 获取当前的流程实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        // 如果流程已经结束，则得到结束节点
        if (Objects.isNull(processInstance)) {
            HistoricProcessInstance pi = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(processId).singleResult();

            processDefinitionId = pi.getProcessDefinitionId();
        } else {
            // 如果流程没有结束，则取当前活动节点
            // 根据流程实例ID获得当前处于活动状态的ActivityId合集
            ProcessInstance pi = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(processId).singleResult();
            processDefinitionId = pi.getProcessDefinitionId();
        }

        // 获得活动的节点
        List<HistoricActivityInstance> highLightedFlowList = historyService
                .createHistoricActivityInstanceQuery()
                .processInstanceId(processId)
                .orderByHistoricActivityInstanceStartTime().asc().list();

        List<String> highLightedFlows = new ArrayList<>();
        List<String> highLightedNodes = new ArrayList<>();
        //高亮线
        for (HistoricActivityInstance tempActivity : highLightedFlowList) {
            if ("sequenceFlow".equals(tempActivity.getActivityType())) {
                //高亮线
                highLightedFlows.add(tempActivity.getActivityId());
            } else {
                //高亮节点
                highLightedNodes.add(tempActivity.getActivityId());
            }
        }

        //获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        ProcessEngineConfiguration configuration = processEngine.getProcessEngineConfiguration();
        //获取自定义图片生成器
        ProcessDiagramGenerator diagramGenerator = new CustomProcessDiagramGenerator();
        //  ProcessDiagramGenerator diagramGenerator = new DefaultProcessDiagramGenerator();
        InputStream in = diagramGenerator
                .generateDiagram(bpmnModel, "png", highLightedNodes, highLightedFlows, configuration.getActivityFontName(),
                        configuration.getLabelFontName(), configuration.getAnnotationFontName(), configuration.getClassLoader(), 1.0, true);
        return in;
    }

    /*
    / 完成任务
     */

    @Override
    public void complete(taskVo taskVO) {
        System.err.println(taskVO);
        //当前查询的任务
        Task task = taskService.createTaskQuery().taskId(taskVO.getTaskId()).singleResult();
        taskService.addComment(task.getId(),task.getProcessInstanceId(),taskVO.getComment());
        Map<String,Object> variables = new HashMap<>();
        variables.put("approvd",taskVO.getApprovd());
        variables.put("persongemail",taskVO.getPersongemail());
        variables.put("comment","您发起的流程因："+taskVO.getComment()+"：被拒绝，请再仔细审查");
        taskService.complete(task.getId(),variables);
    }

    @Override
    public void completetongyi(taskVo taskVO) {
        //当前查询的任务
        Task task = taskService.createTaskQuery().taskId(taskVO.getTaskId()).singleResult();
        taskService.addComment(task.getId(),task.getProcessInstanceId(),taskVO.getComment());
        Map<String,Object> variables = new HashMap<>();
        variables.put("approvd",taskVO.getApprovd());
        variables.put("assignee2",taskVO.getPerson());
        taskService.complete(task.getId(),variables);
    }

    @Override
    public List<FlowTaskDto> finishedList(String gongHao) {
        List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery()
                .includeProcessVariables()
                .finished()
                .taskAssignee(gongHao)
                .orderByHistoricTaskInstanceStartTime()
                .desc()
                .list();

        List<FlowTaskDto> list = new ArrayList<>();
        if(historicTaskInstances != null && historicTaskInstances.size() > 0){
            for (HistoricTaskInstance historicTaskInstance : historicTaskInstances) {
                FlowTaskDto flowTask = new FlowTaskDto();
                //  查询 当前的Task信息
                flowTask.setTaskId(historicTaskInstance.getId());
                // 处理人的ID， 约定账号唯一
                flowTask.setAssigneeId(gongHao);
                flowTask.setAssigneeName(historicTaskInstance.getAssignee());
                flowTask.setCreateTime(historicTaskInstance.getCreateTime());
                // 任务审批耗时
                flowTask.setDuration(historicTaskInstance.getDurationInMillis()/1000+"秒");

            /*Map<String, VariableInstance> variableInstances = taskService.getVariableInstances(historicTaskInstance.getId());
            // 绑定对应的流程变量
            flowTask.setVariableInstances(variableInstances);*/
                // 绑定流程变量
                Map<String, Object> processVariables = historicTaskInstance.getProcessVariables();
                flowTask.setVariables(processVariables);

                flowTask.setProcInsId(historicTaskInstance.getProcessInstanceId());
                flowTask.setTaskName(historicTaskInstance.getName());
                flowTask.setExecutionId(historicTaskInstance.getExecutionId());
                flowTask.setTaskDefKey(historicTaskInstance.getTaskDefinitionKey());

                // 查询流程定义的信息
                ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                        .processDefinitionId(historicTaskInstance.getProcessDefinitionId())
                        .singleResult();
                flowTask.setProcDefId(historicTaskInstance.getProcessDefinitionId());
                flowTask.setProcDefName(processDefinition.getName());
                flowTask.setProcDefVersion(processDefinition.getVersion());
                flowTask.setDeployId(processDefinition.getDeploymentId());

                // 流程发起人的信息
                HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                        .processInstanceId(historicTaskInstance.getProcessInstanceId())
                        .singleResult();
                // 获取任务的发起人
//                String startUserName = historicProcessInstance.getStartUserId();
//                User startUser = userService.queryByUserName(startUserName);
                flowTask.setStartUserId(gongHao);

                //flowTask.setStartUserName(startUser.getNickName());
                flowTask.setStartTime(historicProcessInstance.getStartTime());

                List<HistoricTaskInstanceDto> historicTaskInstanceDtos = new ArrayList<>();
                // 查询当前任务的流转信息
                List<HistoricTaskInstance> taskHiInstances = historyService.createHistoricTaskInstanceQuery()
                        .processInstanceId(historicTaskInstance.getProcessInstanceId())
                        .orderByHistoricTaskInstanceStartTime()
                        .asc()
                        .list();
                for (HistoricTaskInstance taskHiInstance : taskHiInstances) {
                    HistoricTaskInstanceDto dto = new HistoricTaskInstanceDto();
                    dto.setTaskId(taskHiInstance.getId());
                    dto.setTaskName(taskHiInstance.getName());
                    dto.setFinishTime(taskHiInstance.getEndTime());
                    if(taskHiInstance.getDurationInMillis() != null){
                        dto.setDuration(taskHiInstance.getDurationInMillis()/1000 + "秒");
                    }
//                    User user1 = userService.queryByUserName(taskHiInstance.getAssignee());
//                    dto.setAssigneeName(user1.getNickName());
                    // 还需要根据 HistoricTaskInstance 找到对应的 审批意见
                    List<Comment> processInstanceComments = taskService.getProcessInstanceComments(historicTaskInstance.getProcessInstanceId());
                    for (Comment comment : processInstanceComments) {
                        if(comment.getTaskId().equals(taskHiInstance.getId())){
                            // 审批意见
                            String fullMessage = comment.getFullMessage();
                            dto.setComment(fullMessage);
                        }
                    }
                    historicTaskInstanceDtos.add(dto);
                }
                flowTask.setTransferRecords(historicTaskInstanceDtos);
                //flowTask.setSt
                list.add(flowTask);
               // System.err.println(flowTask);
            }
        }


        return list;
    }

    @Override
    public void tongyiQingjia(taskVo taskVo) {
        //当前查询的任务
        Task task = taskService.createTaskQuery().taskId(taskVo.getTaskId()).singleResult();
        taskService.addComment(task.getId(),task.getProcessInstanceId(),taskVo.getComment());
        Map<String,Object> variables = new HashMap<>();
        variables.put("approvd",taskVo.getApprovd());
        taskService.complete(task.getId(),variables);
    }

    @Override
    public void jujueQingJia(taskVo taskVo) {
//        System.err.println(taskVO);
        //当前查询的任务
        Task task = taskService.createTaskQuery().taskId(taskVo.getTaskId()).singleResult();
        taskService.addComment(task.getId(),task.getProcessInstanceId(),taskVo.getComment());
        Map<String,Object> variables = new HashMap<>();
        variables.put("approvd",taskVo.getApprovd());
        taskService.complete(task.getId(),variables);
    }

    @Override
    public void tongyiXuQIu(taskVo taskVo) {
        //当前查询的任务
        Task task = taskService.createTaskQuery().taskId(taskVo.getTaskId()).singleResult();
        taskService.addComment(task.getId(),task.getProcessInstanceId(),taskVo.getComment());
        Map<String,Object> variables = new HashMap<>();
        variables.put("approvd",taskVo.getApprovd());
        taskService.complete(task.getId(),variables);
    }

    @Override
    public void jujueXuQIu(taskVo taskVo) {
//当前查询的任务
        Task task = taskService.createTaskQuery().taskId(taskVo.getTaskId()).singleResult();
        taskService.addComment(task.getId(),task.getProcessInstanceId(),taskVo.getComment());
        Map<String,Object> variables = new HashMap<>();
        variables.put("approvd",taskVo.getApprovd());
        taskService.complete(task.getId(),variables);
    }


}
